package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;


	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		Query query=Query.query(Criteria.where("userId").is(userId));
		Sort updateTime = Sort.by(Sort.Direction.DESC, "updateTime");
		query.with(updateTime);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		if(null==userListenProcess){
			return  null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 存储数据
		map.put("albumId", userListenProcess.getAlbumId());
		map.put("trackId", userListenProcess.getTrackId());
		// 返回数据
		return map;
	}
	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//根据用户id和声音id查询用户的声音进度
		Query query = new Query();
//		Query query=Query.query(Criteria.where("userId").is(userId).where("trackId").is(userListenProcessVo.getTrackId()));
		query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId()));
		System.out.println("query = " + query);
		UserListenProcess userListenProcess = this.mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		System.out.println("userListenProcess = " + userListenProcess);
		if(null!=userListenProcess){
			//设置更新时间
			userListenProcess.setUpdateTime(new Date());
			//设置声音播放进度
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			mongoTemplate.save(userListenProcess, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		}else{
			/*//创建一个新的用户播放进度
			UserListenProcess userListenProcess1=new UserListenProcess();
			//BeanUtils.copyProperties(userListenProcessVo,userListenProcess);
			userListenProcess1.setId(ObjectId.get().toString());
			userListenProcess1.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess1.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess1.setUserId(userId);
			userListenProcess1.setIsShow(1);
			userListenProcess1.setCreateTime(new Date());
			userListenProcess1.setUpdateTime(new Date());
			mongoTemplate.save(userListenProcess1, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));*/
			//	创建对象
			userListenProcess = new UserListenProcess();
			//	进行属性拷贝
			BeanUtils.copyProperties(userListenProcessVo, userListenProcess);
			//	设置Id
			userListenProcess.setId(ObjectId.get().toString());
			//	设置用户Id
			userListenProcess.setUserId(userId);
			//	设置是否显示
			userListenProcess.setIsShow(1);
			//	创建时间
			userListenProcess.setCreateTime(new Date());
			//	更新时间
			userListenProcess.setUpdateTime(new Date());
			//	保存数据
			mongoTemplate.save(userListenProcess, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		}

		//为声音播放设置一个控制，防止恶意刷播放量
		String key="userId:"+userId+":trackId:"+userListenProcessVo.getTrackId();
		//我们对声音的播放量，主要用到的就是这个key，所以value是什么不重要
		Boolean ifAbsent = this.redisTemplate.opsForValue().setIfAbsent(key, 1, 24, TimeUnit.HOURS);
		if(ifAbsent){
			//设置成功，可以对声音的播放量进行操作
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-",""));
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			//异步发送消息//我们将更新的数据封装在了TrackStatVo里面
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
	}

	//todo 获取声音的进度
	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//查询条件
//		Query query = Query.query(Criteria.where("userId").is(userId).and("trackId").is(trackId));
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));
		//调用mangodb,获取声音进度
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class,
				MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		if(null !=userListenProcess){
			return userListenProcess.getBreakSecond();
		}
		return new BigDecimal("0");
	}
}
